package com.lagou.filter;

import com.lagou.obj.RequestCountObj;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RefreshScope
public class RegistryLimitFilter implements GlobalFilter {

    @Value("${limit.count}")
    private int limitCount;

    @Value("${limit.minute}")
    private int limitMinute;

    private static Map<String, RequestCountObj> requestCodeMap = new ConcurrentHashMap();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        String path = uri.getPath();
        if(path.contains("/user/register")){
            HttpHeaders headers = request.getHeaders();
            List<String> ipList = headers.get("real-ip");
            if (ipList != null && ipList.size() > 0){
                String ip = ipList.get(0);
                RequestCountObj requestCountObj = requestCodeMap.get(ip);
                if(requestCountObj == null){
                    requestCountObj = new RequestCountObj();
                    requestCountObj.setCount(0);
                    requestCountObj.setTime(System.currentTimeMillis());
                    requestCodeMap.put(ip, requestCountObj);
                }
                if(isExceedOfLimit(requestCountObj)){
                    ServerHttpResponse response = exchange.getResponse();
                    response.setStatusCode(HttpStatus.FORBIDDEN);
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 403);
                    DataBuffer wrap = response.bufferFactory().wrap(map.toString().getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
        }
        return chain.filter(exchange);
    }

    private boolean isExceedOfLimit(RequestCountObj requestCountObj){
        long currentTimeMillis = System.currentTimeMillis();
        if ((currentTimeMillis - requestCountObj.getTime()) < limitMinute*60000){
            int count = requestCountObj.getCount();
            if(count >= limitCount)
                return true;
            requestCountObj.setCount(++count);
        }else{
            requestCountObj.setTime(currentTimeMillis);
            requestCountObj.setCount(1);
        }
        return false;
    }

}
